<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/1
 * Time: 11:03
 * 域的操作
 */
class Domains_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    /**
     * @param $data
     * @return bool
     */
    public function addIpv4($data)
    {
        //添加同标准域一样的数据
        //处理ip地址
        $bin = null;
        for ($i = 1; $i <= 32; $i++)
        {
            $bin .= $data['ipv4_cidr'] >= $i ? '1' : '0';
        }
        $binshi = bindec($bin);
        $str = ip2long($data['ipv4_network']);
        $re = ($str | ~($binshi));
        $return = array();
        for ($i = ($str + 1); $i < $re; $i++)
        {
            $return[] = long2ip($i);
        }
        //添加域
        foreach($return as $k=>$v)
        {
            $me = explode('.',$v);
            $return[$k] = $me[2].'.'.$me[1].'.'.$me[0].'.in-addr.arpa';
        }
        $ipData = array_unique($return);
        foreach($ipData as $ip)
        {   $id = $this->add($data,$ip);
            if($id)
            {
                $data['domain_id_son'] = $id;
            }else
            {
                return false;
            }
            //添加PTR记录
            if($data['ipv4_autofill_domain'])
            {
                self::_addPtr($data);
            }
            if(isset($data['ipv4_autofill_forward']))//添加A记录
            {
                $data['domain_description'] = $data['domain_description']."(".$data['ipv4_network'].'/'.$data['ipv4_cidr'].")";//描述
                self::_addA($data);
            }
        }
        return true;
    }
    /**
     * @param $data
     * @param $domain_name
     * @return bool
     * 添加域
     */
    public function add($data,$domain_name)
    {
        $domain_description = $data['domain_description'];//描述
        $soa_hostmaster = $data['soa_hostmaster'];//电邮管理地址
        $soa_serial = $data['soa_serial'];//域序列号
        $soa_refresh = $data['soa_refresh'];//刷新定时器
        $soa_retry = $data['soa_retry'];//刷新重试超时
        $soa_expire = $data['soa_expire'];//到期定时器
        $soa_default_ttl = $data['soa_default_ttl'];//默认记录ttl
        $group_id = $data['id_group'];//group_id数组
        //添加dns_domain数据库
        $addData = array(
            'domain_name' => $domain_name,
            'domain_description' => $domain_description,
            'soa_hostmaster' => $soa_hostmaster,
            'soa_serial' => $soa_serial,
            'soa_refresh' => $soa_refresh,
            'soa_retry' => $soa_retry,
            'soa_expire' => $soa_expire ,
            'soa_default_ttl' => $soa_default_ttl
        );
        $this->db->trans_begin();
        $this->db->insert('dns_domains',$addData);
        $id = $this->db->insert_id();
        if($id>0)
        {
            foreach($group_id as $v)
            {
                $group[] = array(
                    'id_domain' => $id,
                    'id_group' => $v
                );
            }
            $this->db->insert_batch('dns_domains_groups',$group);
        }
        //根据组id获取所有的名称服务器名字
        $group_str = 0;//保存组id的字符串
        if($group_id)
        {
            $group_str =  implode(',',$group_id);
        }
        $where = "id_group in(".$group_str.") and server_record =1";
        $groupName = $this->db->select('server_name')->from('name_servers')
                        ->where($where)
                        ->get()
                        ->result_array();
        $server = array();//保存添加dns_records表中的数据
        if($groupName)
        {
            //查看域的信息
            if($id>0)
            {
               $domainsData = $this->db->select()->from('dns_domains')
                   ->where('id',$id)
                   ->get()
                   ->result_array();
                $domains = $domainsData[0];
                foreach($groupName as $val)
                {
                    $server[] = array(
                        'id_domain' => $id,
                        'name' => $domains['domain_name'],
                        'type' => 'NS',
                        'content' => $val['server_name'],
                        'ttl' => 86400,
                        'prio' => 0
                    );
                }
                //向dns_records表中插入数据
                $this->db->insert_batch('dns_records',$server);
            }
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return false;
        }
        else
        {
            $this->db->trans_commit();
            return $id;
        }

    }
    /**\
     * @return array
     * 获取组列表
     */
    public function getGroupList()
    {
        $rows = $this->db->select()->from('name_servers_groups')
            ->get()
            ->result_array();
        return $rows;
    }
    /**
     * @param $page
     * @param $pagesize
     * 获取域列表
     * @return result
     */
    public function getDomainsList($page,$pagesize)
    {
        $dnsDomains = $this->db->select()->from('dns_domains')
            ->limit($pagesize,($page-1)*$pagesize)
            ->get()->result_array();
        $num = $this->db->select()->from('dns_domains')
            ->get()->num_rows();
        return [
            'num' => $num,
            'domainsList'=>$dnsDomains,
        ];
    }

    /**
     * @param int $id
     * @return array
     * 获取单个数据详情
     */
    public function getIdData($id)
    {
        $rows = $this->db->select('dns_domains.*,dns_domains_groups.id_group')->from('dns_domains')
            ->join('dns_domains_groups','dns_domains.id = dns_domains_groups.id_domain')
            ->where('dns_domains.id',$id)
            ->get()
            ->result_array();
        if($rows)
        {

            return $rows[0];
        }
        return false;
    }

    /**
     * @param $id
     * @return array
     * 根据 域的id获取组的信息
     */
    public function getIdGroup($id)
    {
        $row = $this->db->select('id_group')->from('dns_domains_groups')->where('id_domain',$id)
            ->get()
            ->result_array();
        if($row)
        {
            foreach($row as $v)
            {
                $group[]=$v['id_group'];
            }
        }
        return $group;
    }
    /**
     * @param $data
     * @param $group_id
     * @return bool
     * 根据id修改数据
     */
    public function updateIdData($data,$group_id)
    {
        //获取域名
        $domainsName = $data['domain_name'];
        $group_str = implode(',',$group_id);
        //获取名称服务器
        $where = "name_servers_groups.id in(".$group_str.") and server_record =1";
        $nameServers = $this->db->select('server_name')->from('name_servers_groups')
            ->join('name_servers','name_servers.id_group = name_servers_groups.id')
            ->where($where)
            ->get()
            ->result_array();
        //
        $this->db->trans_begin();//开启事务
        $this->db->replace('dns_domains',$data);
        $this->db->where('id_domain',$data['id']);
        $this->db->delete('dns_domains_groups');
        foreach($group_id as $v)
        {
            $this->db->insert('dns_domains_groups',['id_domain'=> $data['id'],'id_group'=>$v]);
        }
        //删除dns_records原有的数据
        $id_domain = $data['id'];
        $where = "id_domain = $id_domain and type = 'NS' ";
        $this->db->where($where);
        $this->db->delete('dns_records');
        //添加新数据
        foreach($nameServers as $v)
        {
            $this->db->insert('dns_records',
                [
                    'id_domain'=>$data['id'],
                    'name'=>$domainsName,
                    'type'=>'NS',
                    'content'=>$v['server_name'],
                    'ttl'=> 86400,
                    'prio' => 0
                ]
            );
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return false;
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    /**
     * @param $id
     * @return bool
     * 根据id删除数据
     */
    public function delIdData($id)
    {
        $this->db->trans_begin();//开启事务
        $this->db->delete('dns_domains',array('id'=>$id));
        $this->db->delete('dns_records',array('id_domain'=>$id));
        $this->db->delete('dns_domains_groups',array('id_domain'=> $id));
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return false;
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }


    }

    /**
     * @param string $where
     *  @return array
     * 根据where字句查询数据
     */
    public function getWhere($where = '')
    {
        if($where == '')
        {
            $where = ' 1';
        }
        $data = $this->db->select()->from('dns_domains')
            ->where($where)
            ->get()
            ->result_array();
        if($data)
        {
            return $data;
        }else
        {
            return array();
        }

    }
    /**
     * @param $data
     * 添加dns_records表中ptr记录
     */
    private function _addPtr($data)
    {
        $me = explode('.',$data['ipv4_network']);
        for($i =0;$i<255;$i++)
        {
            $arr[] = array(
                'id_domain' => $data['domain_id_son'],
                'name' => $i,
                'type' => 'PTR',
                'content' => $me[0].'-'.$me[1].'-'.$me[2].'-'.$i.'.'.$data['ipv4_autofill_domain'],
                'ttl' => $data['soa_default_ttl'],
                'prio' => 0
            );
        }
        $this->db->insert_batch('dns_records',$arr);
    }

    /**
     * @param $data
     * 添加A记录
     */
    private function _addA($data)
    {
        $me = explode('.',$data['ipv4_network']);
        for($i=0;$i<255;$i++)
        {
            $arr[] = array(
                'id_domain' => $data['domain_id'],
                'name' => $me[0].'-'.$me[1].'-'.$me[2].'-'.$i,
                'type' => 'A',
                'content' => $me[0].'.'.$me[1].'.'.$me[2].'.'.$i,
                'ttl' => $data['soa_default_ttl'],
                'prio' => 0
            );
        }
        $this->db->insert_batch('dns_records',$arr);
    }

    /**
     * 测试方法
     */
    public function test($arr)
    {
        $this->db->insert_batch('nihao',$arr);
    }
}